<script setup>
import {defineProps, ref, defineEmits, watch, computed} from "vue";
import moment from "moment";

const props = defineProps({
  label: String,
  required: {
    type: Boolean,
    default: false
  },
  placeholder: {
    type: String,
    default: '请输入'
  },
  modelValue: {
    type: String,
    default: ''
  },
  readonly: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  rules: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue']);
const showPopup = ref(false);

// picker 显示用的值
const pickerValue = ref(props.modelValue);

// 内部状态用于控制 van-date-picker 的值
// const internalValue = ref(props.modelValue.split('-').map(Number) || []);

const internalValue = computed({
  get() {
    return props.modelValue ? props.modelValue.split('-').map(Number): null;
  },
  set(value) {
    if (!value || value.length === 0) {
      emit('update:modelValue', null);
    } else {
      const [year, month, day] = value;
      const date = moment({ year, month: month - 1, day });
      pickerValue.value = date.format('YYYY-MM-DD');
      emit('update:modelValue', date.format('YYYY-MM-DD'));
    }
  }
});

// 监听 modelValue 变化，同步到 internalValue 和 pickerValue
watch(() => props.modelValue, (newVal) => {
  const dateParts = newVal && newVal.split('-').map(Number);
  internalValue.value = dateParts;
}, {immediate: true});

const onOpen = () => {
  if (props.readonly) return;
  showPopup.value = true;
}

const onConfirm = ({selectedValues}) => {
  const formattedValue = selectedValues.join('-');
  pickerValue.value = formattedValue;
  emit('update:modelValue', formattedValue);
  showPopup.value = false;
}

</script>

<template>
  <van-field
      :label="label"
      v-model="pickerValue"
      name="birthday"
      :placeholder="placeholder"
      @click="onOpen"
      readonly
      required
      :clickable="!readonly"
      :disabled="disabled"
      :rules="rules"
      input-align="center"
  />
  <van-popup v-model:show="showPopup" destroy-on-close position="bottom">
    <van-date-picker
        :model-value="internalValue"
        @confirm="onConfirm"
        @cancel="showPopup = false"
    />
  </van-popup>
</template>

<style scoped lang="scss">

</style>